package com.photoeditor.demo.ui.widget.stash.container;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.DashPathEffect;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.widget.FrameLayout;

import com.common.base.ComponentContext;
import com.common.base.utils.DeviceUtils;
import com.photoeditor.R;
import com.photoeditor.demo.app.AppApplication;
import com.photoeditor.demo.model.bean.EditEmojiBean;
import com.photoeditor.demo.model.bean.EmojiBean;
import com.photoeditor.demo.model.bean.stash.ContainerBean;
import com.photoeditor.demo.model.bean.stash.TextBean;
import com.photoeditor.demo.model.event.ExitAddTextFuntionEvent;
import com.photoeditor.demo.statistics.StatisticsConstant;
import com.photoeditor.demo.statistics.StatisticsUtils;
import com.photoeditor.demo.ui.widget.image.emoji.CanvasEditEmojiView;
import com.photoeditor.demo.ui.widget.image.emoji.IStickerSetting;
import com.photoeditor.demo.util.ImageRectUtils;
import com.photoeditor.demo.util.TouchUtil;

import org.greenrobot.eventbus.EventBus;

import java.lang.ref.WeakReference;
import java.util.Iterator;
import java.util.LinkedList;

/**
 * 容器类 可添加子view,如sticker text
 * Created by Administrator on 2017/6/23 0023.
 */

public class ContainerView extends FrameLayout implements IStickerSetting {

    public static final int BEAN_TYPE_STICKER = 1;
    public static final int BEAN_TYPE_TEXT = 2;
    public static final int BEAN_TYPE_DATE = 3;
    public static final int BEAN_TYPE_TIME = 4;
    public static final int BEAN_TYPE_GIF = 5;
    public static final int BEAN_TYPE_IMAGE = 6;

    //用于标识是否初始化
    private boolean mIsInit = false;

    //本界面的Rect
    private RectF mRect;

    private Paint mBitmapPaint;

    private Paint mBoundPaint;

    //是否画边框
    private boolean mDrawOther = true;

    private boolean mIsClickDelete = false;
    private boolean mIsClickSetting = false;
    private boolean mCanPaint = true;
    private boolean mIsSettingMode = false;
    private CanvasEditEmojiView.StickerEditSettingListener mStickerEditSettingListener;
    private boolean mDrawPaintWidthCircle = false;
    private boolean mDrawPathCircle = false;
    private Paint mRingPaint;
    private Paint mCirclePaint;
    private boolean mStartPaint = false;
    private boolean mIsUsefulPath;
    private CanvasEditEmojiView.StickerEditListener mStickerEditListener;

    public LinkedList<ContainerBean> getBeans() {
        return mBeans;
    }

    //存储当前所有Emoji的数据体
    private LinkedList<ContainerBean> mBeans;

    //边界rect
    private RectF mBoundRect;
    private RectF mBoundRectOfView;
    private ValueAnimator mReBackAnim;
    private ValueAnimator mScaleAnim;
    private int mDeleteIconResId;
    private ValueAnimator mBeanScaleAnimDown;
    private static final float BEAN_SCALE_VALUE = 0.94f;

    public int getSelectIndex() {
        return mSelectIndex;
    }

    private Paint mTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);

    private static final String DELETE_TEXT = AppApplication.getApplication().getString(R.string.drag_to_delete);

    //当前选中的index
    private int mSelectIndex;

    //单点touch down 的坐标
    private float mDownX;
    private float mDownY;
    //多点touch down 的坐标
    //private float mMidX;
    //private float mMidY;

    //操作模式
    private int mMode;
    //无操作
    public static final int MODE_NONE = -1;
    //未选中
    public static final int MODE_SELECT_NONE = 1;
    //当前已经选中直接移动
    public static final int MODE_MOVE = 2;
    //当前已经选中直接旋转或者缩放
    public static final int MODE_SCALE_OR_ROTATION_OR_MOVE = 3;
    //点击
    public static final int MODE_CLICK = 4;
    //动画
    public static final int MODE_ANIMATING = 5;

    private static final int MODE_SCALE_OR_ROTATION = 6;

    public static final int MODE_SELECT_LEFT_OPERATION = 7;
    public static final int MODE_SELECT_RIGHT_OPERATION = 8;
    public static final int MODE_SELECT_TOP_OPERATION = 9;
    public static final int MODE_SELECT_BOTTOM_OPERATION = 10;

    //当前选中的EditTextBean
    private ContainerBean mCurrentTouchBean;

    //用于缓存绘制时的RectF
    private RectF mCacheRect;

    //private RectF mDeleteRect;

    //private RectF mDeleteRectAfterScale = new RectF();

    //操作Drawable
    private Drawable mOperationDrawable;

    private Drawable mSettingDrawable;

    //操作Drawable
    private Drawable mDeleteDrawable;

    //操作Drawable
    private Drawable mTouchLeftDrawable;
    private Drawable mTouchRightDrawable;
    private Drawable mTouchTopDrawable;
    private Drawable mTouchBottomDrawable;

    private static final float DELETE_ICON_SCALE_PARAM = 1.3f;
    private static final float DELETE_ICON_SCALE_PARAM_RE = 0.7f;
    //辅助用
    Matrix m = new Matrix();

    private RectF mDeleteBeanRect = new RectF();

    //private Bitmap mDeleteBitmap;

    private float mDeleteMargin = DeviceUtils.dip2px(ComponentContext.getContext(), 20f);
    private float mDeleteTextMargin = DeviceUtils.dip2px(ComponentContext.getContext(), 14f);

    //是否可以删除
    private boolean mCanDelete = false;
    private boolean mCanDeleteBottom = false;

    //用于更新视图
    public static final int DO_ON_DRAW = 0x101;

    private boolean mClickBean;

    private boolean mClickSpace;

    private Vibrator mVibrator;

    private ContainerListener mContainerListener;

    private ItemSelectedListener mItemSelectedListener;

    //当前bean操作之前的rect
    private RectF mLastRect;

    //是否超出边界
    private boolean mIsOutOfBound = false;

    //编辑页添加文字的交互
    private boolean mAddTextMode = false;

    private boolean mHaveSetting = true;

    public void setAddTextMode(boolean addTextMode, boolean addText) {
        mAddTextMode = addTextMode;
        if (addText && mAddTextMode) {
            addText(new TextBean(getResources().getString(R.string.default_string), mRect.centerX(),
                    mBoundRect == null ? mRect.bottom - DeviceUtils.dip2px(ComponentContext.getContext(), 50) :
                            mBoundRect.bottom - DeviceUtils.dip2px(ComponentContext.getContext(), 50), mDefaultTextColor));
        }
    }

    private DashPathEffect mDashPathEffect;

    public void setContainerListener(ContainerListener containerListener) {
        mContainerListener = containerListener;
    }

    public void setItemSelectedListener(ItemSelectedListener itemSelectedListener) {
        mItemSelectedListener = itemSelectedListener;
    }


    /**
     * 处理更新
     */
    private Handler mHandler = new MyHandler(this);

    private static class MyHandler extends Handler {
        private final WeakReference<View> mRef;

        private MyHandler(View view) {
            this.mRef = new WeakReference<>(view);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == DO_ON_DRAW) {
                if (mRef.get() != null) {
                    mRef.get().postInvalidate();
                }
            }
        }
    }

    public ContainerView(Context context) {
        this(context, null);
    }

    public ContainerView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
        initialize();
    }

    private void initialize() {
        setWillNotDraw(false);
        if (isHardwareAccelerated()) {
            setLayerType(View.LAYER_TYPE_HARDWARE, null);
        }

        mOperationDrawable = getResources().getDrawable(R.drawable.ic_rotate);
        if (mHaveSetting) {
            mSettingDrawable = getResources().getDrawable(R.drawable.ic_sticker_setting);
        }
        mDeleteDrawable = getResources().getDrawable(R.drawable.ic_close_emoji);
        mTouchLeftDrawable = getResources().getDrawable(R.drawable.ic_touch_move_left);
        mTouchRightDrawable = getResources().getDrawable(R.drawable.ic_touch_move_right);
        mTouchTopDrawable = getResources().getDrawable(R.drawable.ic_touch_move_top);
        mTouchBottomDrawable = getResources().getDrawable(R.drawable.ic_touch_move_bottom);

        mCacheRect = new RectF();
        mLastRect = new RectF();
        mVibrator = (Vibrator) getContext().getSystemService(Context.VIBRATOR_SERVICE);
        mBeans = new LinkedList();
        mSelectIndex = -1;

        mTextPaint.setTextSize(DeviceUtils.sp2pxF(ComponentContext.getContext(), 15f));
        mTextPaint.setTextAlign(Paint.Align.CENTER);
//        mTextPaint.setTypeface(FontUtil.CUSTOM_FONT);

        mBitmapPaint = new Paint();
        mBitmapPaint.setAntiAlias(true);
        mBitmapPaint.setFilterBitmap(true);

        mBoundPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mBoundPaint.setColor(getResources().getColor(R.color.image_edit_text_bound_color));
        mBoundPaint.setAntiAlias(true);
        mBoundPaint.setStrokeWidth(DeviceUtils.dip2px(ComponentContext.getContext(), 1));
        mBoundPaint.setStyle(Paint.Style.STROKE);

        mRingPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mRingPaint.setStyle(Paint.Style.STROKE);
        mRingPaint.setColor(Color.WHITE);
        mRingPaint.setStrokeWidth(DeviceUtils.dip2px(ComponentContext.getContext(), 2));

        mCirclePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mCirclePaint.setStyle(Paint.Style.FILL);
        mCirclePaint.setColor(Color.parseColor("#33000000"));

        float dp1 = DeviceUtils.dip2px(ComponentContext.getContext(), 2);
        mDashPathEffect = new DashPathEffect(new float[]{dp1, dp1}, 1);
    }

    public ContainerView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right,
                            int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        if (!mIsInit) {
            mRect = ImageRectUtils.getViewRect(this);
            if (mBoundRect != null) {
                if (mBoundRectOfView == null) {
                    mBoundRectOfView = new RectF();
                }
                mBoundRectOfView.set(mBoundRect.left - mRect.left, mBoundRect.top - mRect.top, mBoundRect.right - mRect.left, mBoundRect.bottom - mRect.top);
            }
            /*mDeleteBitmap = BitmapFactory.decodeResource(getResources(), mDeleteIconResId);
            mDeleteRect = new RectF(mRect.left + mRect.width() / 2 - mDeleteBitmap.getWidth() / 2,
                    mRect.bottom - (mDeleteBitmap.getHeight() + mDeleteMargin + mBottomDeleteHeight),
                    mRect.left + mRect.width() / 2 + mDeleteBitmap.getWidth() / 2,
                    mRect.bottom - mDeleteMargin - mBottomDeleteHeight);*/

            /*m.setScale(0.5f, 0.5f, mDeleteRect.centerX(), mDeleteRect.centerY());
            m.mapRect(mDeleteBeanRect, mDeleteRect);

            m.setScale(DELETE_ICON_SCALE_PARAM, DELETE_ICON_SCALE_PARAM, mDeleteRect.centerX(), mDeleteRect.centerY());
            m.mapRect(mDeleteRectAfterScale, mDeleteRect);*/

            mIsInit = true;
        }
    }

    /**
     * Ontouchevent中调用 用于获取当前选中的对象
     * 这个会切换选中对象
     * 如果切换成功，层次关系需要修改
     * <p>
     * x y是点击的真实坐标
     *
     * @param x
     * @param y
     * @return
     */
    private int getTouchEditTextBeanIndex(float x, float y, boolean distinguishSticker) {
        if (mBeans != null) {
            int len = mBeans.size();
            for (int i = len - 1; i >= 0; i--) {
                ContainerBean bean = mBeans.get(i);
                if (distinguishSticker && bean.getType() != ContainerView.BEAN_TYPE_STICKER) {
                    continue;
                }
                //dst用于存储变换后的点
                float[] dst = new float[2];
                bean.getMatrix().mapPoints(dst, new float[]{x, y});
                RectF vr = bean.getRect();
                if (vr.contains(dst[0], dst[1])) {//匹配成功  需要布局层次关系
                    //把将要选中的放到最后  绘制的时候就会正确
                    mBeans.remove(i);
                    mBeans.addLast(bean);
                    return (len - 1);
                }
            }
        }
        return -1;
    }

    float oldDist = 1f;
    float oldRotation = 0;
    private boolean mIsMoving = false;

    private boolean mTouchable = true;

    //操作之前是否选中
    private boolean mSelectBefore;

    public void setTouchable(boolean touchable) {
        mTouchable = touchable;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (!mTouchable) {
            return false;
        }
        if (mContainerListener != null && event.getAction() == MotionEvent.ACTION_DOWN) {
            mContainerListener.onTouchDown();
        }
        if (!mIsInit || mBeans == null || mBeans.size() == 0) {
            if (mAddTextMode) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        mDownX = event.getX();
                        mDownY = event.getY();
                        mClickSpace = true;
                        break;
                    case MotionEvent.ACTION_MOVE:
                        float nowX = event.getRawX();
                        float nowY = event.getRawY();

                        float dx = nowX - mDownX;
                        float dy = nowY - mDownY;
                        if (Math.abs(dx) >= TouchUtil.OFFSET || Math.abs(dy) >= TouchUtil.OFFSET) {
                            mClickSpace = false;
                        }
                        break;
                    default:
                        if (mClickSpace) {
                            addText(new TextBean(getResources().getString(R.string.default_string), mDownX, mDownY, mDefaultTextColor));
                        }
                        break;
                }
            }
            return mFullTouchable;
        }
        switch (event.getAction() & MotionEvent.ACTION_MASK) {
            case MotionEvent.ACTION_DOWN:
                if (event.getPointerCount() != 1) {
                    break;
                }
                mDownX = event.getRawX();
                mDownY = event.getRawY();
                mDrawOther = true;
                mIsMoving = false;
                mSelectBefore = false;
                if (mSelectIndex >= 0 && mSelectIndex < mBeans.size()) {
                    /**
                     *区域重复，优先上层选中的
                     */
                    mCurrentTouchBean = mBeans.get(mSelectIndex);
                    float[] dst = new float[2];
                    mCurrentTouchBean.getMatrix().mapPoints(dst, new float[]{mDownX, mDownY});
                    RectF vr = mCurrentTouchBean.getRect();

                    RectF leftOperationRect = mCurrentTouchBean.getLeftOperationRect();
                    RectF rightOperationRect = mCurrentTouchBean.getRightOperationRect();
                    RectF topOperationRect = mCurrentTouchBean.getTopOperationRect();
                    RectF bottomOperationRect = mCurrentTouchBean.getBottomOperationRect();

                    float d = (float) Math.sqrt((dst[0] - vr.right) * (dst[0] - vr.right) + (dst[1] - vr.bottom) * (dst[1] - vr.bottom));

                    float deleteDistance = (float) Math.sqrt((dst[0] - vr.left) * (dst[0] - vr.left) + (dst[1] - vr.top) * (dst[1] - vr.top));

                    float settingDistance = (float) Math.sqrt((dst[0] - vr.left) * (dst[0] - vr.left) + (dst[1] - vr.bottom) * (dst[1] - vr.bottom));
                    if (mIsSettingMode) {
                        if (vr.contains(dst[0], dst[1])) {
                            if (mCanPaint) {
                                mStartPaint = true;
                                mIsUsefulPath = false;
                                mDrawPathCircle = false;
                                ((EditEmojiBean) mCurrentTouchBean).setPathStart(mDownX - vr.left, mDownY - vr.top);
                            }
                            mCurrentTouchBean.setIsTouch(true);
                            mMode = MODE_NONE;
                            refresh();
                            return true;
                        } else {
                            int index = getTouchEditTextBeanIndex(mDownX, mDownY, true);
                            if (index != -1) {
                                mSelectIndex = index;
                                mCurrentTouchBean = mBeans.get(mSelectIndex);
                                mCurrentTouchBean.setIsTouch(true);
                                refresh();
                                mMode = MODE_NONE;
                                if (mStickerEditSettingListener != null) {
                                    mStickerEditSettingListener.onSelectOther(mCurrentTouchBean);
                                }
                                return true;
                            } else {
                                mMode = MODE_NONE;
                                mDrawOther = false;
                            }
                        }
                    } else {
                        if (vr.contains(dst[0], dst[1])) {
                            if (d <= EditEmojiBean.RADIUS + TouchUtil.TOUCH_BUTTON_OFFSET) {//按钮
                                mMode = MODE_SCALE_OR_ROTATION;
                            } else if (deleteDistance <= EditEmojiBean.RADIUS + TouchUtil.TOUCH_BUTTON_OFFSET) {
                                mIsClickDelete = true;
                            } else if (mHaveSetting && settingDistance <= EditEmojiBean.RADIUS + TouchUtil.TOUCH_BUTTON_OFFSET) {
                                mIsClickSetting = true;
                            } else if (leftOperationRect.contains(dst[0], dst[1])) {
                                mMode = MODE_SELECT_LEFT_OPERATION;
                            } else if (rightOperationRect.contains(dst[0], dst[1])) {
                                mMode = MODE_SELECT_RIGHT_OPERATION;
                            } else if (topOperationRect.contains(dst[0], dst[1])) {
                                mMode = MODE_SELECT_TOP_OPERATION;
                            } else if (bottomOperationRect.contains(dst[0], dst[1])) {
                                mMode = MODE_SELECT_BOTTOM_OPERATION;
                            } else {
                                mMode = MODE_MOVE;
                                mClickBean = true;
                                mSelectBefore = true;
                                if (mItemSelectedListener != null) {
                                    mItemSelectedListener.onSelected();
                                }
                            }
                            refresh();
                            mCurrentTouchBean.setIsTouch(true);
                            mLastRect.set(mCurrentTouchBean.getRect());
                            if (mContainerListener != null) {
                                mContainerListener.onTouchBeanDown(mCurrentTouchBean);
                            }
                            //startBeanScaleAnimate(1, BEAN_SCALE_VALUE);
                            return true;
                        } else {
                            if (d <= EditEmojiBean.RADIUS + TouchUtil.TOUCH_BUTTON_OFFSET) {//按钮
                                mCurrentTouchBean.setIsTouch(true);
                                refresh();
                                mMode = MODE_SCALE_OR_ROTATION;
                                return true;
                            } else if (mHaveSetting && settingDistance <= EditEmojiBean.RADIUS + TouchUtil.TOUCH_BUTTON_OFFSET) {
                                mCurrentTouchBean.setIsTouch(true);
                                refresh();
                                mIsClickSetting = true;
                                return true;
                            } else if (deleteDistance <= EditEmojiBean.RADIUS + TouchUtil.TOUCH_BUTTON_OFFSET) {
                                mCurrentTouchBean.setIsTouch(true);
                                refresh();
                                mIsClickDelete = true;
                                return true;
                            } else if (leftOperationRect.contains(dst[0], dst[1])) {
                                mCurrentTouchBean.setIsTouch(true);
                                refresh();
                                mMode = MODE_SELECT_LEFT_OPERATION;
                                return true;
                            } else if (rightOperationRect.contains(dst[0], dst[1])) {
                                mCurrentTouchBean.setIsTouch(true);
                                refresh();
                                mMode = MODE_SELECT_RIGHT_OPERATION;
                                return true;
                            } else if (topOperationRect.contains(dst[0], dst[1])) {
                                mCurrentTouchBean.setIsTouch(true);
                                refresh();
                                mMode = MODE_SELECT_TOP_OPERATION;
                                return true;
                            } else if (bottomOperationRect.contains(dst[0], dst[1])) {
                                mCurrentTouchBean.setIsTouch(true);
                                refresh();
                                mMode = MODE_SELECT_BOTTOM_OPERATION;
                                return true;
                            } else {
                                //判断它点到的区域属于哪一个bean
                                int index = getTouchEditTextBeanIndex(mDownX, mDownY, false);
                                if (index != -1) {
                                    mClickBean = true;
                                    mMode = MODE_MOVE;
                                    mSelectIndex = index;
                                    mCurrentTouchBean = mBeans.get(mSelectIndex);
                                    mCurrentTouchBean.setIsTouch(true);
                                    mLastRect.set(mCurrentTouchBean.getRect());
                                    //startBeanScaleAnimate(1, BEAN_SCALE_VALUE);
                                    refresh();
                                    if (mItemSelectedListener != null) {
                                        mItemSelectedListener.onSelected();
                                    }
                                    if (mContainerListener != null) {
                                        mContainerListener.onTouchBeanDown(mCurrentTouchBean);
                                    }
                                    return true;
                                } else {
                                    mMode = MODE_NONE;
                                    mDrawOther = false;
                                    mClickSpace = true;
                                }
                            }
                        }
                    }
                } else {
                    //判断它点到的区域属于哪一个bean
                    int index = getTouchEditTextBeanIndex(mDownX, mDownY, false);
                    if (index != -1) {
                        mClickBean = true;
                        mMode = MODE_MOVE;
                        mSelectIndex = index;
                        mCurrentTouchBean = mBeans.get(mSelectIndex);
                        mCurrentTouchBean.setIsTouch(true);
                        mLastRect.set(mCurrentTouchBean.getRect());
                        //startBeanScaleAnimate(1, BEAN_SCALE_VALUE);
                        refresh();
                        if (mItemSelectedListener != null) {
                            mItemSelectedListener.onSelected();
                        }
                        if (mContainerListener != null) {
                            mContainerListener.onTouchBeanDown(mCurrentTouchBean);
                        }
                        return true;
                    } else {
                        mMode = MODE_NONE;
                        mDrawOther = false;
                        mClickSpace = true;
                    }
                }
                break;
            case MotionEvent.ACTION_POINTER_DOWN:
                oldDist = spacing(event);
                oldRotation = rotation(event);
                int index = getTouchEditTextBeanIndex(event.getX(0) + mRect.left, event.getY(0) + mRect.top, false);
                if (index != -1) {
                    mMode = MODE_SCALE_OR_ROTATION_OR_MOVE;
                    mClickBean = true;
                    mSelectIndex = index;
                    mCurrentTouchBean = mBeans.get(mSelectIndex);
                    mCurrentTouchBean.setIsTouch(true);
                    mLastRect.set(mCurrentTouchBean.getRect());
                    refresh();
                    return true;
                }
                mMode = MODE_NONE;
                mDrawOther = false;
                refresh();
                break;
            case MotionEvent.ACTION_MOVE:
                if (!mIsSettingMode && event.getPointerCount() > 1 && mMode == MODE_SCALE_OR_ROTATION_OR_MOVE) {
                    float newDist = spacing(event);
                    if (mClickBean && Math.abs(newDist - oldDist) <= ViewConfiguration.getTouchSlop()) {
                        return true;
                    }
                    if (mContainerListener != null) {
                        mContainerListener.onOperation();
                    }
                    mClickBean = false;
                    float rotation = rotation(event) - oldRotation;
                    float scale = newDist / oldDist;
                    mCurrentTouchBean.setDegree(rotation);
                    mCurrentTouchBean.setScale(scale);
                    oldRotation = rotation(event);
                    oldDist = newDist;
                    refresh();
                    return true;
                } else {
                    float nowX = event.getRawX();
                    float nowY = event.getRawY();

                    float dx = nowX - mDownX;
                    float dy = nowY - mDownY;
                    if (mIsMoving || Math.abs(dx) >= TouchUtil.OFFSET || Math.abs(dy) >= TouchUtil.OFFSET) {
                        mIsMoving = true;
                        if (mIsSettingMode && mStartPaint) {
                            mIsUsefulPath = true;
                            mDrawPathCircle = true;
                            RectF vr = mCurrentTouchBean.getRect();
                            ((EditEmojiBean) mCurrentTouchBean).setPathMove(mDownX - vr.left, mDownY - vr.top, nowX - vr.left, nowY - vr.top);
                            mDownX = nowX;
                            mDownY = nowY;
                            refresh();

                        } else {
                            mIsClickDelete = false;
                            mIsClickSetting = false;
                            if (mMode == MODE_MOVE) {
                                if (mContainerListener != null) {
                                    mContainerListener.onOperation();
                                }
                                mClickBean = false;
                                mClickSpace = false;
                                mCurrentTouchBean.move(dx, dy);
                                mIsOutOfBound = isOutBoundRect(mCurrentTouchBean.getRect());
                                mDownX = nowX;
                                mDownY = nowY;
                                refresh();
                            } else if (mMode == MODE_SCALE_OR_ROTATION) {
                                if (mContainerListener != null) {
                                    mContainerListener.onOperation();
                                }
                                mClickBean = false;
                                mClickSpace = false;
                                mCurrentTouchBean.dealScaleAndRotation(mDownX, mDownY, nowX, nowY);
                                mDownX = nowX;
                                mDownY = nowY;
                                refresh();
                            } else if (mMode == MODE_SELECT_LEFT_OPERATION) {
                                if (mContainerListener != null) {
                                    mContainerListener.onOperation();
                                }
                                mClickBean = false;
                                mClickSpace = false;
                                float[] dst = new float[2];
                                mCurrentTouchBean.getMatrix().mapPoints(dst, new float[]{mDownX, mDownY});

                                float[] sda = new float[2];
                                mCurrentTouchBean.getMatrix().mapPoints(sda, new float[]{nowX, nowY});

                                dx = sda[0] - dst[0];

                                mCurrentTouchBean.operationLeft(dx);
                                mDownX = nowX;
                                mDownY = nowY;
                                refresh();
                            } else if (mMode == MODE_SELECT_RIGHT_OPERATION) {
                                if (mContainerListener != null) {
                                    mContainerListener.onOperation();
                                }
                                mClickBean = false;
                                mClickSpace = false;
                                float[] dst = new float[2];
                                mCurrentTouchBean.getMatrix().mapPoints(dst, new float[]{mDownX, mDownY});

                                float[] sda = new float[2];
                                mCurrentTouchBean.getMatrix().mapPoints(sda, new float[]{nowX, nowY});

                                dx = sda[0] - dst[0];

                                mCurrentTouchBean.operationRight(dx);
                                mDownX = nowX;
                                mDownY = nowY;
                                refresh();
                            } else if (mMode == MODE_SELECT_TOP_OPERATION) {
                                if (mContainerListener != null) {
                                    mContainerListener.onOperation();
                                }
                                mClickBean = false;
                                mClickSpace = false;
                                float[] dst = new float[2];
                                mCurrentTouchBean.getMatrix().mapPoints(dst, new float[]{mDownX, mDownY});

                                float[] sda = new float[2];
                                mCurrentTouchBean.getMatrix().mapPoints(sda, new float[]{nowX, nowY});

                                dy = sda[1] - dst[1];

                                mCurrentTouchBean.operationTop(dy);
                                mDownX = nowX;
                                mDownY = nowY;
                                refresh();
                            } else if (mMode == MODE_SELECT_BOTTOM_OPERATION) {
                                if (mContainerListener != null) {
                                    mContainerListener.onOperation();
                                }
                                mClickBean = false;
                                mClickSpace = false;
                                float[] dst = new float[2];
                                mCurrentTouchBean.getMatrix().mapPoints(dst, new float[]{mDownX, mDownY});

                                float[] sda = new float[2];
                                mCurrentTouchBean.getMatrix().mapPoints(sda, new float[]{nowX, nowY});

                                dy = sda[1] - dst[1];

                                mCurrentTouchBean.operationBottom(dy);
                                mDownX = nowX;
                                mDownY = nowY;
                                refresh();
                            }
                        }
                    }
                }

                /*if(mMode == MODE_MOVE){
                    float nowX = event.getX();
                    float nowY = event.getY();
                    if(mClickBean && Math.abs(nowX - mDownX) <= ViewConfiguration.getTouchSlop() && Math.abs(nowY - mDownY) <= ViewConfiguration.getTouchSlop()){
                        return true;
                    }
                    mIsMoving = true;
                    if(mContainerListener != null){
                        mContainerListener.onOperation();
                    }
                    mClickBean = false;
                    mIsOutOfBound = isOutBoundRect(mCurrentTouchBean.getRect());
                    if(mDeleteRect.contains(nowX, nowY)){
                        if(!mCanDelete) {
                            //刚进入删除圈内
                            mCanDelete = true;
                            startScaleAnimate(DELETE_ICON_SCALE_PARAM_RE, 1f);
                            if(mVibrator.hasVibrator()){
                                mVibrator.vibrate(20);
                            }
                        }
                    }else {
                        if(mCanDelete){
                            //刚出删除圈
                            mCanDelete = false;
                            startScaleAnimate(1f, DELETE_ICON_SCALE_PARAM_RE);
                        }
                    }
                    if(mCurrentTouchBean.getRect().top > (mRect.bottom-mBottomDeleteHeight)){
                        if(!mCanDeleteBottom){
                            mCanDeleteBottom = true;
                            startScaleAnimate(DELETE_ICON_SCALE_PARAM_RE, 1f);
                            if(mVibrator.hasVibrator()){
                                mVibrator.vibrate(20);
                            }
                        }
                    }else{
                        if(mCanDeleteBottom){
                            mCanDeleteBottom = false;
                            startScaleAnimate(1f, DELETE_ICON_SCALE_PARAM_RE);
                        }
                    }
                    if(!mCanDelete){
                        mCurrentTouchBean.move(nowX - mDownX, nowY - mDownY);
                        mDownX = nowX;
                        mDownY = nowY;
                    }
                    refresh();
                    return true;
                }else if (mMode == MODE_SCALE_OR_ROTATION_OR_MOVE) {
                    if (event.getPointerCount() > 1) {
                        float newDist = spacing(event);
                        if (mClickBean && Math.abs(newDist - oldDist) <= ViewConfiguration.getTouchSlop()) {
                            return true;
                        }
                        if (mContainerListener != null) {
                            mContainerListener.onOperation();
                        }
                        mClickBean = false;
                        mIsOutOfBound = isOutBoundRect(mCurrentTouchBean.getRect());
                        float rotation = rotation(event) - oldRotation;
                        float scale = newDist / oldDist;
                        float nowMidX = (event.getX(0) + event.getX(1)) / 2;
                        float nowMidY = (event.getY(0) + event.getY(1)) / 2;
                        mCurrentTouchBean.move(nowMidX - mMidX, nowMidY - mMidY);
                        mCurrentTouchBean.setDegree(rotation);
                        mCurrentTouchBean.setScale(scale);
                        mMidX = nowMidX;
                        mMidY = nowMidY;
                        oldRotation = rotation(event);
                        oldDist = newDist;
                        refresh();
                        return true;
                    }
                }*/
                break;
            case MotionEvent.ACTION_CANCEL:
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_POINTER_UP:
                boolean ret = mFullTouchable;
                if (mMode == MODE_MOVE || mMode == MODE_SCALE_OR_ROTATION
                        || mMode == MODE_SELECT_LEFT_OPERATION
                        || mMode == MODE_SELECT_RIGHT_OPERATION
                        || mMode == MODE_SELECT_TOP_OPERATION
                        || mMode == MODE_SELECT_BOTTOM_OPERATION
                        || mMode == MODE_SCALE_OR_ROTATION_OR_MOVE) {
                    ret = true;
                }

                /*if (mMode == MODE_MOVE) {
                    startBeanScaleAnimate(BEAN_SCALE_VALUE, 1);
                }*/
                if (mCurrentTouchBean != null) {
                    mCurrentTouchBean.setIsTouch(false);
                }

                if (mIsClickDelete) {
                    mIsClickDelete = false;
                    deleteBean(mSelectIndex);
                }
                if (mIsClickSetting && mCurrentTouchBean.getType() == ContainerView.BEAN_TYPE_STICKER) {
                    mIsClickSetting = false;
                    mIsSettingMode = true;
                    if (mStickerEditListener != null) {
                        mStickerEditListener.onClickSetting();
                    }
                }
                if (event.getPointerCount() == 1 && mClickBean) {
                    if (mAddTextMode) {
                        if (getCurrentBean() != null && getCurrentBean() instanceof TextBean && getResources().getString(R.string.default_string).equals(((TextBean) mCurrentTouchBean).getString())) {
                        }
                    }
                    if (mContainerListener != null) {
                        mContainerListener.onBeanClick(mCurrentTouchBean, mSelectBefore);
                        mMode = MODE_CLICK;
                    }
                }
                if (mAddTextMode && event.getPointerCount() == 1 && mClickSpace) {
                    if (mBoundRect == null || (mBoundRect != null && mBoundRect.contains(mDownX, mDownY))) {
                        //点击空白区域
                        if (getCurrentBean() != null && getCurrentBean() instanceof TextBean && getResources().getString(R.string.default_string).equals(((TextBean) mCurrentTouchBean).getString())) {
                            addText(new TextBean(getResources().getString(R.string.default_string), mDownX, mDownY, mDefaultTextColor));
                        } else {
                            addText(new TextBean(getResources().getString(R.string.default_string), mDownX, mDownY, mDefaultTextColor));
                        }
                    }
                }
                if (mContainerListener != null && ret) {
                    mContainerListener.onOperationFinish();
                }
                if (mBoundRect != null && !mCanDelete && mIsOutOfBound) {
                    startTranslateAnimate(mCurrentTouchBean.getRect());
                }
                mIsOutOfBound = false;
                /*if (mCanDelete || mCanDeleteBottom) {
                    startScaleAnimate(1f, DELETE_ICON_SCALE_PARAM_RE);
                    deleteBean(mSelectIndex);
                    mCanDelete = false;
                }*/

                mIsMoving = false;
                mClickBean = false;
                mClickSpace = false;
                if (!mIsSettingMode) {
                    mMode = MODE_NONE;
                } else {
                    if (mStartPaint && mIsUsefulPath) {
                        mDrawPathCircle = false;
                        ((EditEmojiBean) mCurrentTouchBean).savePath();
                        if (mStickerEditSettingListener != null) {
                            mStickerEditSettingListener.onPaintFinish();
                        }
                    }
                }
                mStartPaint = false;
                refresh();
                return ret;
        }
        return mFullTouchable;
    }

    //接收所有事件
    private boolean mFullTouchable = false;

    public void setFullTouchable(boolean fullTouchable) {
        mFullTouchable = fullTouchable;
    }

    public void setTextColor(int color) {
        mTextPaint.setColor(color);
    }

    private boolean isOutBoundRect(RectF r) {
        RectF rect = (mBoundRect == null || mBoundRect.isEmpty()) ? mRect : mBoundRect;
        return rect.top >= r.bottom || rect.bottom <= r.top
                || rect.left >= r.right || rect.right <= r.left;

    }

    private void deleteBeansOutOfBound() {
        if (mBeans != null && !mBeans.isEmpty()) {
            Iterator<ContainerBean> iterator = mBeans.iterator();
            while (iterator.hasNext()) {
                ContainerBean next = iterator.next();
                if (isOutBoundRect(next.getRect())) {
                    iterator.remove();
                    next.onDestroy();
                }
            }
            mSelectIndex = -1;
        }
    }

    private void startBeanScaleAnimate(float from, float to) {
        final RectF lastRectBeforeScale = mCurrentTouchBean.getLastRectBeforeScale();
        if (mBeanScaleAnimDown != null && mBeanScaleAnimDown.isRunning()) {
            mBeanScaleAnimDown.cancel();
            mCurrentTouchBean.scaleTo(lastRectBeforeScale, from);
            refresh();
        }
        mBeanScaleAnimDown = ValueAnimator.ofFloat(from, to);
        mBeanScaleAnimDown.setDuration(30);
        mBeanScaleAnimDown.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float lastScaleValue = (float) animation.getAnimatedValue();
                mCurrentTouchBean.scaleTo(lastRectBeforeScale, lastScaleValue);
                refresh();
            }
        });
        mBeanScaleAnimDown.start();
    }

    private void startTranslateAnimate(RectF currentRect) {
        final float dx = mLastRect.centerX() - currentRect.centerX();
        final float dy = mLastRect.centerY() - currentRect.centerY();
        final float ratio = dy / dx;
        mCurrentTouchBean.getLastRectBeforeScale().offset(dx, dy);
        mReBackAnim = ValueAnimator.ofFloat(1, 0);
        mReBackAnim.setDuration(100);
        mReBackAnim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                mMode = MODE_ANIMATING;
                float value = dx * (float) animation.getAnimatedValue();
                mCurrentTouchBean.moveTo(mLastRect, value, value * ratio);
                refresh();
            }
        });
        mReBackAnim.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationCancel(Animator animation) {
                mMode = MODE_NONE;
                mCurrentTouchBean.moveTo(mLastRect, dx, dy);
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                mMode = MODE_NONE;
            }

        });
        mReBackAnim.start();
    }

    /*private void startScaleAnimate(float from, float to) {
        mScaleAnim = ValueAnimator.ofFloat(from, to);
        mScaleAnim.setDuration(100);
        mScaleAnim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float value = (float) animation.getAnimatedValue();
                m.setScale(value, value, mDeleteRectAfterScale.centerX(), mDeleteRectAfterScale.centerY());
                RectF rect = new RectF();
                m.mapRect(rect, mDeleteRectAfterScale);
                mDeleteRect = rect;
                refresh();
            }
        });
        mScaleAnim.start();
    }*/

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        int len = mBeans.size();
        if (len == 0) {
            return;
        }
        for (int i = 0; i < len; i++) {
            if (i != mSelectIndex) {
                ContainerBean bean = mBeans.get(i);
                RectF dst = bean.getRect();
                mCacheRect.left = dst.left - mRect.left;
                mCacheRect.top = dst.top - mRect.top;
                mCacheRect.right = dst.right - mRect.left;
                mCacheRect.bottom = dst.bottom - mRect.top;
                int count = canvas.save();
                if (mBoundRectOfView != null && mMode == MODE_NONE) {
                    canvas.clipRect(mBoundRectOfView);
                }
                canvas.rotate(bean.getDegree(), mCacheRect.centerX(), mCacheRect.centerY());
                if (bean.getType() == ContainerView.BEAN_TYPE_STICKER) {
                    mBitmapPaint.setColorFilter(generateColorMatrixColorFilter((EditEmojiBean) bean));
                } else {
                    mBitmapPaint.setColorFilter(null);
                }
                Bitmap bitmap = bean.getBitmap();
                if (bitmap != null && !bitmap.isRecycled()) {
                    canvas.drawBitmap(bitmap, null, mCacheRect, mBitmapPaint);
                }
                canvas.restoreToCount(count);
            }
        }
        if (mSelectIndex < len && mSelectIndex >= 0) {
            ContainerBean bean = mBeans.get(mSelectIndex);
            RectF dst = bean.getRect();
            RectF br = bean.getButtonRect();
            RectF sr = bean.getSettingRect();
            RectF dr = bean.getDeleteRect();
            RectF leftR = bean.getLeftOperationRect();
            RectF rightR = bean.getRightOperationRect();
            RectF topR = bean.getTopOperationRect();
            RectF bottomR = bean.getBottomOperationRect();
            mCacheRect.left = dst.left - mRect.left;
            mCacheRect.top = dst.top - mRect.top;
            mCacheRect.right = dst.right - mRect.left;
            mCacheRect.bottom = dst.bottom - mRect.top;
            int count1 = canvas.save();
            if (mBoundRectOfView != null && mMode == MODE_NONE) {
                canvas.clipRect(mBoundRectOfView);
            }

            if (mCanDelete) {
                Bitmap bitmap = bean.getBitmap();
                if (bitmap != null && !bitmap.isRecycled()) {
                    canvas.drawBitmap(bitmap, null, mDeleteBeanRect, mBitmapPaint);
                }
            } else {
                canvas.rotate(bean.getDegree(), mCacheRect.centerX(), mCacheRect.centerY());
                if (bean.getType() == ContainerView.BEAN_TYPE_STICKER) {
                    mBitmapPaint.setColorFilter(generateColorMatrixColorFilter((EditEmojiBean) bean));
                } else {
                    mBitmapPaint.setColorFilter(null);
                }
                Bitmap bitmap = bean.getBitmap();
                if (bitmap != null && !bitmap.isRecycled()) {
                    canvas.drawBitmap(bitmap, null, mCacheRect, mBitmapPaint);
                }
            }
            canvas.restoreToCount(count1);
            if (mIsSettingMode) {
                if (bean.getType() == ContainerView.BEAN_TYPE_STICKER) {
                    int count2 = canvas.save();
                    canvas.rotate(bean.getDegree(), mCacheRect.centerX(), mCacheRect.centerY());
                    mBoundPaint.setPathEffect(mDashPathEffect);
                    canvas.drawRect(mCacheRect, mBoundPaint);
                    mBoundPaint.setPathEffect(null);
                    canvas.restoreToCount(count2);
                }
            } else {
                if (mDrawOther && mMode != MODE_SCALE_OR_ROTATION_OR_MOVE) {
                    int count2 = canvas.save();
                    canvas.rotate(bean.getDegree(), mCacheRect.centerX(), mCacheRect.centerY());
                    canvas.drawRect(mCacheRect, mBoundPaint);
                    if (mMode == MODE_SCALE_OR_ROTATION) {
                        mOperationDrawable.setBounds((int) (br.left - mRect.left + 0.5f), (int) (br.top - mRect.top + 0.5f), (int) (br.right - mRect.left + 0.5f), (int) (br.bottom - mRect.top + 0.5f));
                        mOperationDrawable.draw(canvas);
                    } else if (mMode == MODE_SELECT_LEFT_OPERATION || mMode == MODE_SELECT_RIGHT_OPERATION) {
                        mTouchLeftDrawable.setBounds((int) (leftR.left - mRect.left + 0.5f), (int) (leftR.top - mRect.top + 0.5f), (int) (leftR.right - mRect.left + 0.5f), (int) (leftR.bottom - mRect.top + 0.5f));
                        mTouchLeftDrawable.draw(canvas);
                        mTouchRightDrawable.setBounds((int) (rightR.left - mRect.left + 0.5f), (int) (rightR.top - mRect.top + 0.5f), (int) (rightR.right - mRect.left + 0.5f), (int) (rightR.bottom - mRect.top + 0.5f));
                        mTouchRightDrawable.draw(canvas);
                    } else if (mMode == MODE_SELECT_TOP_OPERATION || mMode == MODE_SELECT_BOTTOM_OPERATION) {
                        mTouchTopDrawable.setBounds((int) (topR.left - mRect.left + 0.5f), (int) (topR.top - mRect.top + 0.5f), (int) (topR.right - mRect.left + 0.5f), (int) (topR.bottom - mRect.top + 0.5f));
                        mTouchTopDrawable.draw(canvas);
                        mTouchBottomDrawable.setBounds((int) (bottomR.left - mRect.left + 0.5f), (int) (bottomR.top - mRect.top + 0.5f), (int) (bottomR.right - mRect.left + 0.5f), (int) (bottomR.bottom - mRect.top + 0.5f));
                        mTouchBottomDrawable.draw(canvas);
                    } else {
                        mOperationDrawable.setBounds((int) (br.left - mRect.left + 0.5f), (int) (br.top - mRect.top + 0.5f), (int) (br.right - mRect.left + 0.5f), (int) (br.bottom - mRect.top + 0.5f));
                        mOperationDrawable.draw(canvas);
                        if (mHaveSetting && bean.getType() == BEAN_TYPE_STICKER) {
                            mSettingDrawable.setBounds((int) (sr.left - mRect.left + 0.5f), (int) (sr.top - mRect.top + 0.5f), (int) (sr.right - mRect.left + 0.5f), (int) (sr.bottom - mRect.top + 0.5f));
                            mSettingDrawable.draw(canvas);
                        }
                        mDeleteDrawable.setBounds((int) (dr.left - mRect.left + 0.5f), (int) (dr.top - mRect.top + 0.5f), (int) (dr.right - mRect.left + 0.5f), (int) (dr.bottom - mRect.top + 0.5f));
                        mDeleteDrawable.draw(canvas);
                        if (bean.getType() != BEAN_TYPE_TEXT) {
                            mTouchLeftDrawable.setBounds((int) (leftR.left - mRect.left + 0.5f), (int) (leftR.top - mRect.top + 0.5f), (int) (leftR.right - mRect.left + 0.5f), (int) (leftR.bottom - mRect.top + 0.5f));
                            mTouchLeftDrawable.draw(canvas);
                            mTouchRightDrawable.setBounds((int) (rightR.left - mRect.left + 0.5f), (int) (rightR.top - mRect.top + 0.5f), (int) (rightR.right - mRect.left + 0.5f), (int) (rightR.bottom - mRect.top + 0.5f));
                            mTouchRightDrawable.draw(canvas);
                            mTouchTopDrawable.setBounds((int) (topR.left - mRect.left + 0.5f), (int) (topR.top - mRect.top + 0.5f), (int) (topR.right - mRect.left + 0.5f), (int) (topR.bottom - mRect.top + 0.5f));
                            mTouchTopDrawable.draw(canvas);
                            mTouchBottomDrawable.setBounds((int) (bottomR.left - mRect.left + 0.5f), (int) (bottomR.top - mRect.top + 0.5f), (int) (bottomR.right - mRect.left + 0.5f), (int) (bottomR.bottom - mRect.top + 0.5f));
                            mTouchBottomDrawable.draw(canvas);
                        }
                    }
                    canvas.restoreToCount(count2);
                }
            }
            if (bean instanceof EditEmojiBean) {
                drawPaintWidthCircle(canvas, ((EditEmojiBean) bean).getPaintWidthRadius());
                drawPathCircle(canvas, ((EditEmojiBean) bean).getPaintWidthRadius());
            }
        }
        /*if (MODE_MOVE == mMode && mIsMoving) {
            //删除
            canvas.drawBitmap(mDeleteBitmap, null, mDeleteRect, mBitmapPaint);
            canvas.drawText(DELETE_TEXT, mDeleteRect.centerX(), mDeleteRect.top - mDeleteTextMargin, mTextPaint);
        }*/
    }

    public ColorMatrixColorFilter generateColorMatrixColorFilter(EditEmojiBean bean) {
        if (bean.isShowSrc()) {
            EditEmojiBean.AdjustParam lastParam = bean.getLastParam();
            ColorMatrix hueMatrix = new ColorMatrix();
            //修改色相   0 red 1 green 2 blue
            hueMatrix.setRotate(0, 0);
            hueMatrix.setRotate(1, 0);
            hueMatrix.setRotate(2, 0);
            //修改饱和度
            ColorMatrix saturationMatrix = new ColorMatrix();
            saturationMatrix.setSaturation(1);
            //修改亮度
            ColorMatrix lumMatrix = new ColorMatrix();
            //r g b a    1 表示全不透明
            lumMatrix.setScale(1, 1, 1, 1 - 0);

            //组合Matrix
            ColorMatrix imageMatrix = new ColorMatrix();
            imageMatrix.postConcat(hueMatrix);
            imageMatrix.postConcat(saturationMatrix);
            imageMatrix.postConcat(lumMatrix);

            return new ColorMatrixColorFilter(imageMatrix);
        } else {
            EditEmojiBean.AdjustParam lastParam = bean.getLastParam();
            ColorMatrix hueMatrix = new ColorMatrix();
            //修改色相   0 red 1 green 2 blue
            hueMatrix.setRotate(0, lastParam.tone);
            hueMatrix.setRotate(1, lastParam.tone);
            hueMatrix.setRotate(2, lastParam.tone);
            //修改饱和度
            ColorMatrix saturationMatrix = new ColorMatrix();
            saturationMatrix.setSaturation(lastParam.saturation);
            //修改亮度
            ColorMatrix lumMatrix = new ColorMatrix();
            //r g b a    1 表示全不透明
            lumMatrix.setScale(lastParam.brightness, lastParam.brightness, lastParam.brightness, 1 - lastParam.alpha);

            //组合Matrix
            ColorMatrix imageMatrix = new ColorMatrix();
            imageMatrix.postConcat(hueMatrix);
            imageMatrix.postConcat(saturationMatrix);
            imageMatrix.postConcat(lumMatrix);

            return new ColorMatrixColorFilter(imageMatrix);
        }
    }

    //画笔宽度示意图
    private void drawPaintWidthCircle(Canvas canvas, float radius) {
        if (mDrawPaintWidthCircle) {
            RectF rect = mBoundRect == null ? mRect : mBoundRect;
            canvas.drawCircle(rect.centerX(), rect.centerY(), radius, mCirclePaint);
            canvas.drawCircle(rect.centerX(), rect.centerY(), radius, mRingPaint);
        }
    }

    //画笔示意图
    private void drawPathCircle(Canvas canvas, float radius) {
        if (mDrawPathCircle) {
            canvas.drawCircle(mDownX - mRect.left, mDownY - mRect.top, radius, mRingPaint);
        }
    }

    //刷新
    public void refresh() {
        if (!mHandler.hasMessages(DO_ON_DRAW)) {
            mHandler.sendEmptyMessage(DO_ON_DRAW);
        }
    }

    public void setHaveSetting(boolean haveSetting) {
        mHaveSetting = haveSetting;
    }

    /**
     * 添加Emoji表情
     *
     * @param emoji
     */
    public void addSticker(EmojiBean emoji) {
        EditEmojiBean bean = new EditEmojiBean(mBoundRect == null ? mRect : mBoundRect, emoji);
        mBeans.addLast(bean);
        mDrawOther = true;
        mSelectIndex = mBeans.size() - 1;
        refresh();
        if (mContainerListener != null) {
            mContainerListener.onAdd(bean);
        }
    }

    /**
     * 提前添加数据 不能实时刷新
     *
     * @param emoji
     * @param rectF
     * @param degree
     */
    public void addSticker(EmojiBean emoji, RectF rectF, float degree) {
        if (isOutBoundRect(rectF)) return;
        EditEmojiBean bean = new EditEmojiBean(rectF, emoji, degree);
        mBeans.addLast(bean);
        mSelectIndex = mBeans.size() - 1;
        if (mContainerListener != null) {
            mContainerListener.onAdd(bean);
        }
    }

    /**
     * 删除Emoji表情
     *
     * @param position
     */
    public void deleteBean(int position) {
        ContainerBean removeBean = null;
        if (position < mBeans.size() && position >= 0) {
            removeBean = mBeans.remove(position);
            removeBean.onDestroy();
            mSelectIndex = -1;
            if (mAddTextMode) {
                boolean hasTextBean = false;
                for (ContainerBean bean : mBeans) {
                    if (bean.getType() == BEAN_TYPE_TEXT) {
                        hasTextBean = true;
                        break;
                    }
                }
                if (!hasTextBean) {
                    //没有文字了，退出添加文字功能
                    EventBus.getDefault().post(new ExitAddTextFuntionEvent());
                    mMode = MODE_NONE;
                    mAddTextMode = false;
                }
            } else {
                refresh();
            }
        }
        if (mContainerListener != null) {
            mContainerListener.onDelete(position, removeBean);
        }
    }

    public void deleteBean(ContainerBean bean) {
        if (mBeans.contains(bean)) {
            bean.onDestroy();
            mBeans.remove(bean);
            mSelectIndex = -1;
            refresh();
        }
    }

    public void deleteEmptyTextBean() {
        if (mBeans != null && mBeans.size() > 0) {
            Iterator<ContainerBean> iterator = mBeans.iterator();
            while (iterator.hasNext()) {
                ContainerBean bean = iterator.next();
                if (bean instanceof TextBean) {
                    if (getResources().getString(R.string.default_string).equals(((TextBean) bean).getString())) {
                        iterator.remove();
                        bean.onDestroy();
                        mSelectIndex = -1;
                    }
                }
            }
            refresh();
        }
    }

    public void clearAll() {
        if (mBeans != null && mBeans.size() > 0) {
            for (ContainerBean bean : mBeans) {
                bean.onDestroy();
            }
            mBeans.clear();
            mSelectIndex = -1;
            refresh();
        }
    }

    public void selectNone() {
        if (mSelectIndex != -1) {
            mSelectIndex = -1;
            refresh();
        }
    }

    /**
     * emoji卸载后的处理
     *
     * @param pkgName
     */
    public void removeUninstallSticker(String pkgName) {
        if (mBeans == null) return;
        int size = mBeans.size();
        for (int i = 0; i < size; ) {
            ContainerBean editEmojiBean = mBeans.get(i);
            if (editEmojiBean != null && editEmojiBean instanceof EditEmojiBean && ((EditEmojiBean) editEmojiBean).getEmojiBean() != null) {
                String beanPkgName = ((EditEmojiBean) editEmojiBean).getEmojiBean().getPackageName();
                if (beanPkgName != null && beanPkgName.equals(pkgName)) {
                    mBeans.remove(i);
                    size--;
                } else {
                    i++;
                }
            }
        }
        mSelectIndex = mBeans.size() - 1;
        refresh();
    }


    public void addText(TextBean textBean) {
        addContainerBean(textBean);
    }

    public void addContainerBean(ContainerBean bean) {
        mBeans.addLast(bean);
        mSelectIndex = mBeans.size() - 1;
        mDrawOther = true;
        refresh();
        if (mContainerListener != null) {
            mContainerListener.onAdd(bean);
        }
    }

    public RectF getRect() {
        return mRect;
    }

    public void setBoundRect(RectF boundRect) {
        mBoundRect = boundRect;
        if (mIsInit) {
            if (mBoundRectOfView == null) {
                mBoundRectOfView = new RectF();
            }
            mBoundRectOfView.set(mBoundRect.left - mRect.left, mBoundRect.top - mRect.top, mBoundRect.right - mRect.left, mBoundRect.bottom - mRect.top);
        }
        deleteBeansOutOfBound();
        refresh();
        /*if (boundRect.bottom < DeviceUtils.getScreenHeightPx(ComponentContext.getContext())
                && (DeviceUtils.getScreenHeightPx(ComponentContext.getContext()) - boundRect.bottom) > mDeleteMargin) {
            mDeleteIconResId = R.drawable.white_hold_del;
            setTextColor(getResources().getColor(R.color.title_color));
        } else {
            mDeleteIconResId = R.drawable.hold_del;
            setTextColor(Color.WHITE);
        }*/
    }

    public RectF getBoundRect() {
        return mBoundRect;
    }


    public boolean hasGif() {
        boolean hasGif = false;
        for (ContainerBean bean : mBeans) {
            if (bean.getType() == ContainerView.BEAN_TYPE_GIF) {
                hasGif = true;
                break;
            }
        }
        return hasGif;
    }

    public int getDuration() {
        int maxDuration = 0;
        for (ContainerBean bean : mBeans) {
            if (bean.getType() == ContainerView.BEAN_TYPE_GIF) {
            }
        }
        if (maxDuration == 0) {
            return maxDuration;
        }
        while (maxDuration < 1000) {
            maxDuration *= 2;
        }
        return maxDuration;
    }

    public float getFrame() {
        float maxFrame = 0;
        for (ContainerBean bean : mBeans) {
            if (bean.getType() == ContainerView.BEAN_TYPE_GIF) {
            }
        }
        return maxFrame;
    }

    /**
     * 用于获取合成好的图片
     *
     * @return
     */
    public Bitmap getDstBitmap(Bitmap srcBitmap, float scale, int position) {
        if (srcBitmap != null && !srcBitmap.isRecycled() && mBeans != null && mBeans.size() > 0) {

            Bitmap bitmap = Bitmap.createBitmap(srcBitmap.getWidth(), srcBitmap.getHeight(), Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(bitmap);
            Paint p = new Paint(Paint.ANTI_ALIAS_FLAG);
            p.setAntiAlias(true);
            p.setFilterBitmap(true);

            canvas.drawBitmap(srcBitmap, 0, 0, p);

            RectF cacheRect = new RectF();
            for (ContainerBean bean : mBeans) {
                RectF dst = bean.getRect();
                cacheRect.left = dst.left;
                cacheRect.top = dst.top;
                cacheRect.right = dst.right;
                cacheRect.bottom = dst.bottom;
                canvas.save();
                canvas.scale(scale, scale);
                canvas.rotate(bean.getDegree(), cacheRect.centerX(), cacheRect.centerY());
                if (mBoundRect != null) {
                    canvas.translate(mRect.left - mBoundRect.left, mRect.top - mBoundRect.top);
                }
                if (bean.getType() == ContainerView.BEAN_TYPE_GIF) {
                } else {
                    canvas.drawBitmap(bean.getBitmap(), null, cacheRect, p);
                }
                canvas.restore();
            }
            return bitmap;
        }
        return srcBitmap;
    }

    /**
     * 用于获取合成好的图片
     *
     * @return
     */
    public void getDstBitmap(Canvas canvas, float scale, int position) {
        if (mBeans != null && mBeans.size() > 0) {

            Paint p = new Paint(Paint.ANTI_ALIAS_FLAG);
            p.setAntiAlias(true);
            p.setFilterBitmap(true);

            RectF cacheRect = new RectF();
            for (ContainerBean bean : mBeans) {
                RectF dst = bean.getRect();
                cacheRect.left = dst.left;
                cacheRect.top = dst.top;
                cacheRect.right = dst.right;
                cacheRect.bottom = dst.bottom;
                canvas.save();
                canvas.scale(scale, scale);
                if (mBoundRect != null) {
                    canvas.translate(mRect.left - mBoundRect.left, mRect.top - mBoundRect.top);
                }
                canvas.rotate(bean.getDegree(), cacheRect.centerX(), cacheRect.centerY());
                if (bean.getType() == ContainerView.BEAN_TYPE_GIF) {
                } else {
                    canvas.drawBitmap(bean.getBitmap(), null, cacheRect, p);
                }
                canvas.restore();
            }
            return;
        }
        return;
    }

    @Override
    public void setShowSrc(boolean showSrc) {
        ContainerBean canvasBean = getCurrentBean();
        if (canvasBean != null && canvasBean.getType() == ContainerView.BEAN_TYPE_STICKER) {
            ((EditEmojiBean) canvasBean).setShowSrc(showSrc);
            refresh();
        }
    }

    @Override
    public void resetParam() {
        ContainerBean canvasBean = getCurrentBean();
        if (canvasBean != null && canvasBean.getType() == ContainerView.BEAN_TYPE_STICKER) {
            ((EditEmojiBean) canvasBean).resetParam();
            refresh();
        }
    }

    @Override
    public void resetPaint() {
        ContainerBean canvasBean = getCurrentBean();
        if (canvasBean != null && canvasBean.getType() == ContainerView.BEAN_TYPE_STICKER) {
            ((EditEmojiBean) canvasBean).resetPaint();
            refresh();
        }
    }

    @Override
    public void updateTone(float tone) {
        ContainerBean canvasBean = getCurrentBean();
        if (canvasBean != null && canvasBean.getType() == ContainerView.BEAN_TYPE_STICKER) {
            ((EditEmojiBean) canvasBean).setTone(tone);
        }
        refresh();
    }

    @Override
    public void updateSaturation(float st) {
        ContainerBean canvasBean = getCurrentBean();
        if (canvasBean != null && canvasBean.getType() == ContainerView.BEAN_TYPE_STICKER) {
            ((EditEmojiBean) canvasBean).setSaturation(st);
        }
        refresh();
    }

    @Override
    public void updateBrightness(float brightness) {
        ContainerBean canvasBean = getCurrentBean();
        if (canvasBean != null && canvasBean.getType() == ContainerView.BEAN_TYPE_STICKER) {
            ((EditEmojiBean) canvasBean).setBrightness(brightness);
            refresh();
        }
    }

    @Override
    public void updateAlpha(float a) {
        ContainerBean canvasBean = getCurrentBean();
        if (canvasBean != null && canvasBean.getType() == ContainerView.BEAN_TYPE_STICKER) {
            ((EditEmojiBean) canvasBean).setAlpha(a);
            refresh();
        }
    }

    @Override
    public void setPaintMode(int mode) {
        ContainerBean canvasBean = getCurrentBean();
        if (canvasBean != null && canvasBean.getType() == ContainerView.BEAN_TYPE_STICKER) {
            ((EditEmojiBean) canvasBean).setPaintMode(mode);
        }
    }

    @Override
    public void setPaintStyle(int style) {
        ContainerBean canvasBean = getCurrentBean();
        if (canvasBean != null && canvasBean.getType() == ContainerView.BEAN_TYPE_STICKER) {
            ((EditEmojiBean) canvasBean).setPaintStyle(style);
        }
    }

    @Override
    public void saveParam() {
        ContainerBean canvasBean = getCurrentBean();
        if (canvasBean != null && canvasBean.getType() == ContainerView.BEAN_TYPE_STICKER) {
            ((EditEmojiBean) canvasBean).saveParam();
            refresh();
        }
    }

    @Override
    public void removeLastParam() {
        ContainerBean canvasBean = getCurrentBean();
        if (canvasBean != null && canvasBean.getType() == ContainerView.BEAN_TYPE_STICKER) {
            ((EditEmojiBean) canvasBean).removeLastParam();
            refresh();
        }
    }

    @Override
    public void removeLastPaint() {
        ContainerBean canvasBean = getCurrentBean();
        if (canvasBean != null && canvasBean.getType() == ContainerView.BEAN_TYPE_STICKER) {
            ((EditEmojiBean) canvasBean).removeLastPaint();
            refresh();
        }
    }

    public void updateTextBeanString(String string) {
        ContainerBean canvasBean = getCurrentBean();
        if (canvasBean != null && canvasBean.getType() == ContainerView.BEAN_TYPE_TEXT) {
            ((TextBean) canvasBean).updateString(string);
            refresh();
        }
    }

    public void updateTextBeanColor(int textColor, int bgColor, int checkId, int style) {
        ContainerBean canvasBean = getCurrentBean();
        if (canvasBean != null && canvasBean.getType() == ContainerView.BEAN_TYPE_TEXT) {
            TextBean textBean = (TextBean) canvasBean;
            textBean.updateColor(textColor, bgColor);
            textBean.updateStyle(style);
            textBean.updateCheckId(checkId);
            refresh();
        }
    }

    public void updateFont(Typeface typeface, String fontKey) {
        ContainerBean canvasBean = getCurrentBean();
        if (canvasBean != null && canvasBean.getType() == ContainerView.BEAN_TYPE_TEXT) {
            TextBean textBean = (TextBean) canvasBean;
            textBean.updateFont(typeface, fontKey);
            refresh();
        }
    }

    @Override
    public ContainerBean getCurrentBean() {
        if (mSelectIndex != -1 && mSelectIndex < mBeans.size()) {
            return mBeans.get(mSelectIndex);
        } else {
            return null;
        }
    }

    @Override
    public void setCanPaint(boolean canPaint) {
        mCanPaint = canPaint;
    }

    @Override
    public void cancelSettingMode() {
        mIsSettingMode = false;
        for (ContainerBean bean : mBeans) {
            if (bean instanceof EditEmojiBean) {
                ((EditEmojiBean) bean).reset();
            }
        }
        refresh();
    }

    @Override
    public void saveSettingMode() {
        mIsSettingMode = false;
        for (ContainerBean bean : mBeans) {
            if (bean instanceof EditEmojiBean) {
                ((EditEmojiBean) bean).save();
            }
        }
        refresh();
    }

    public void setStickerEditListener(CanvasEditEmojiView.StickerEditListener stickerEditListener) {
        mStickerEditListener = stickerEditListener;
    }

    @Override
    public void setStickerEditSettingListener(CanvasEditEmojiView.StickerEditSettingListener listener) {
        mStickerEditSettingListener = listener;
    }

    @Override
    public void updatePaintWidthProgress(int progress) {
        mSelectIndex = Math.min(mBeans.size() - 1, Math.max(mSelectIndex, 0));//数据保护
        ContainerBean canvasBean = mBeans.get(mSelectIndex);
        if (canvasBean != null && canvasBean.getType() == ContainerView.BEAN_TYPE_STICKER) {
            ((EditEmojiBean) canvasBean).setPaintWidth(progress);
            refresh();
        }
    }

    @Override
    public void setDrawPaintWidthCircle(boolean drawPaintWidthCircle) {
        mDrawPaintWidthCircle = drawPaintWidthCircle;
    }

    private float mBottomDeleteHeight = 0;

    public void setBottomDeleteHeight(int height) {
        this.mBottomDeleteHeight = height;
    }

    // 触碰两点间距离
    private float spacing(MotionEvent event) {
        float x = event.getX(0) - event.getX(1);
        float y = event.getY(0) - event.getY(1);
        return (float) Math.sqrt(x * x + y * y);
    }

    // 取旋转角度
    private float rotation(MotionEvent event) {
        double delta_x = (event.getX(0) - event.getX(1));
        double delta_y = (event.getY(0) - event.getY(1));
        double radians = Math.atan2(delta_y, delta_x);
        return (float) Math.toDegrees(radians);
    }

    //判断两点触控能否对目标操作
    private boolean checkCanOpt(float x1, float y1, float x2, float y2, RectF src) {
        if ((x1 < src.left && x2 < src.left) || (x1 > src.right && x2 > src.right)) {
            return false;
        }
        if ((y1 < src.top && y2 < src.top) || (y1 > src.bottom && y2 > src.bottom)) {
            return false;
        }
        return true;
    }

    public void onDestory() {
        if (mScaleAnim != null && mScaleAnim.isRunning()) {
            mScaleAnim.cancel();
        }
        mScaleAnim = null;
        if (mBeanScaleAnimDown != null && mBeanScaleAnimDown.isRunning()) {
            mBeanScaleAnimDown.cancel();
        }
        mBeanScaleAnimDown = null;
        if (mReBackAnim != null && mReBackAnim.isRunning()) {
            mReBackAnim.cancel();
        }
        mReBackAnim = null;
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
        }
        mCurrentTouchBean = null;
        /*if (mDeleteBitmap != null && !mDeleteBitmap.isRecycled()) {
            mDeleteBitmap.recycle();
        }*/
        mContainerListener = null;
        clearAll();
    }

    public interface ContainerListener {

        void onBeanClick(ContainerBean bean, boolean selectBefore);

        void onTouchDown();

        void onTouchBeanDown(ContainerBean bean);

        void onClickSpace();

        //move
        void onOperation();

        /**
         * onTouchBeanUp
         */
        void onOperationFinish();

        void onAdd(ContainerBean bean);

        void onDelete(int pos, ContainerBean bean);
    }

    public interface ItemSelectedListener {
        void onSelected();
    }

    public void statistics() {
        for (int i = 0; i < mBeans.size(); i++) {
            ContainerBean bean = mBeans.get(i);
            if (bean instanceof TextBean) {
                TextBean textBean = (TextBean) bean;
                StatisticsUtils.statisicsCustomFunction(StatisticsConstant.UMENG_CUSTOM_EVENT_FUNC_FONT_BAR_APPLY,
                        StatisticsConstant.UMENG_CUSTOM_EVENT_KEY_CLICK, textBean.getFontKey());
            }
        }
    }

    private int mDefaultTextColor = Color.WHITE;

    public void setDefaultTextColor(boolean isBlack) {
        mDefaultTextColor = isBlack ? Color.BLACK : Color.WHITE;
    }

    public boolean hasStickerBean() {
        boolean hasSticker = false;
        if (mBeans != null && !mBeans.isEmpty()) {
            for (ContainerBean bean : mBeans) {
                if (bean.getType() == ContainerView.BEAN_TYPE_STICKER
                        || bean.getType() == ContainerView.BEAN_TYPE_GIF
                        || bean.getType() == ContainerView.BEAN_TYPE_DATE
                        || bean.getType() == ContainerView.BEAN_TYPE_TIME) {
                    hasSticker = true;
                    break;
                }
            }
        }
        return hasSticker;
    }

    public boolean hasTextBean() {
        boolean hasText = false;
        if (mBeans != null && !mBeans.isEmpty()) {
            for (ContainerBean bean : mBeans) {
                if (bean.getType() == ContainerView.BEAN_TYPE_TEXT) {
                    hasText = true;
                    break;
                }
            }
        }
        return hasText;
    }

}
